<?php

!defined('IN_SYSTEM') && exit('Access denied');

class class_db {
    private $db = NULL;
    private $td = false;
	private $sql = '';
    public function __construct($host,$user,$pass,$name) {
        if (is_null($this->db)) {
            try {
                $this->db = @new PDO("mysql:dbname={$name};charset=utf8;host={$host}",$user,$pass);
                $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $this->db->exec('set names utf8');
            } catch(PDOException $e) {
                $this->halt($e->getMessage());
            }
        }
    }

    public function fetch($sql) {
        $query = $this->query($sql);
        $rowset = $query->fetch(PDO::FETCH_ASSOC);
        return $rowset ? $rowset : array();
    }

    public function fetchAll($sql) {
        $query = $this->query($sql);
        $rowset = $query->fetchAll(PDO::FETCH_ASSOC);
        return $rowset ? $rowset : array();
    }

    public function fetchCol($sql,$num=0) {
        $query = $this->query($sql);
        return $query->fetchColumn($num);
    }

    public function insertId(){
        return $this->db->lastInsertId();
    }

    public function runSql($sql) {
        try {
			$this->sql = $sql;
            return $this->db->exec($sql);
        } catch(PDOException $e) {
            $this->halt($e->getMessage());
        }
    }

    public function beginTransaction() {
        $this->db->beginTransaction();
        $this->td = TRUE;
    }

    public function rollback() {
        $this->db->rollback();
    }

    public function commit() {
        $this->db->commit();
    }

    private function query($sql) {
        try {
			$this->sql = $sql;
            return $this->db->query($sql);
        } catch(PDOException $e) {
            $this->halt($e->getMessage());
        }
    }

    private function halt($error) {
        if($this->td) $this->db->rollback();
        if (AJAX) {
            $jd = array();
            $jd['state'] = -800;
            $jd['message'] = $error.$this->sql;
            exit(json_encode($jd));
        } else {
            exit($error."<b>{$this->sql}</b>");
        }
    }
}